import json

with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()

text = text.replace("\"", "").replace("'", "").replace(",", "")
texts = text.split("\n")
texts = [i.strip() for i in texts][:20]


data = []
for t in texts:
    data.append({"term": {"news_keywords": t}})

ret = {
  "query": {
      "bool": {
        "should": data,
        "minimum_should_match": "30%"
      }
    }
}
from datetime import datetime, timedelta

# 当前日期
current_date = datetime.now()
def get_start_end(days):
  # 一年前的日期
  one_year_ago = current_date - timedelta(days=days)

  # 格式化日期为 yyyy-MM-dd
  start_date = one_year_ago.strftime('%Y-%m-%d')
  end_date = current_date.strftime('%Y-%m-%d')
  return start_date, end_date



if __name__ == "__main__":
  import sys
  if len(sys.argv) == 2:
    minimum = int((sys.argv[1]) * 100) + "%"
    ret["query"]["bool"]["minimum_should_match"] = minimum
  if len(sys.argv) == 3:
    time = sys.argv[2]
    time = time.lower()
    num, unit = time.split("_")
    num = int(num)
    if unit == 'm':
      num *= 30
    elif unit == 'y':
      num *= 365
    start_date, end_date = get_start_end(num)
    ret["query"]["bool"]["filter"] = {
      "range": {
        "news_publicdate": {
          "gte": start_date,
          "lte": end_date
        }
      }
    }
  with open("data.json", "w", encoding="utf-8") as f:
    json.dump(ret, f, ensure_ascii=False, indent=4)